package com.microservice.user.controller;

import com.microservice.api.common.PageResult;
import com.microservice.api.common.Result;
import com.microservice.api.user.dto.UserInfoDTO;
import com.microservice.api.user.dto.UserUpdateDTO;
import com.microservice.api.wechat.ArticleServiceClient;
import com.microservice.user.dto.ArticleReviewRequest;
import com.microservice.api.wechat.WechatDraftServiceClient;
import com.microservice.api.wechat.dto.ArticleDTO;
import com.microservice.api.wechat.dto.DraftAddResponse;
import com.microservice.common.annotation.RequirePermission;
import com.microservice.common.annotation.RequireRole;
import com.microservice.user.service.UserService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

/**
 * 管理员接口控制器
 * 需要ROLE_ADMIN或ROLE_AUDITOR角色才能访问
 */
@Slf4j
@RestController
@RequestMapping("/admin")
@RequireRole(value = {"ROLE_ADMIN", "ROLE_AUDITOR"}, logical = RequireRole.Logical.OR)
public class AdminController {

    @Resource
    private ArticleServiceClient articleServiceApi;
    @Resource
    private WechatDraftServiceClient wechatDraftServiceApi;
    @Resource
    private UserService userService;

    /**
     * 审核文章（通过/拒绝）
     * 支持记录审核人员和拒绝原因
     * 
     * @param request 审核请求参数（JSON格式）
     * @return 审核结果
     */
    @PostMapping("/review")
    public Result<String> reviewArticle(@RequestBody ArticleReviewRequest request) {
        try {
            // 自动获取当前审核人员信息
            Long reviewerId = com.microservice.common.utils.AuthUtils.requireUserId();
            String reviewerName = com.microservice.common.utils.AuthUtils.getCurrentUsername();
            
            log.info("审核人员 {} (ID:{}) 审核文章 {}, 状态: {}", 
                    reviewerName, reviewerId, request.getArticleId(), request.getStatus());
            
            // 调用审核接口
            return articleServiceApi.reviewArticle(
                    request.getArticleId(), 
                    request.getStatus(), 
                    request.getRejectReason(), 
                    reviewerId, 
                    "系统管理员");
        } catch (Exception e) {
            log.error("审核文章失败", e);
            return Result.error("审核失败: " + e.getMessage());
        }
    }
    
    /**
     * 通过审核并添加到草稿箱
     */
    @GetMapping("/addDraft/{articleId}")
    public Result<DraftAddResponse> addDraftAndApprove(@PathVariable Long articleId) {
        try {
            // 自动获取当前审核人员信息
            Long reviewerId = com.microservice.common.utils.AuthUtils.requireUserId();
            String reviewerName = com.microservice.common.utils.AuthUtils.getCurrentUsername();
            
            log.info("通过审核文章: {}", articleId);
            Result<ArticleDTO> articleDTOResult = articleServiceApi.getById(articleId);
            if (articleDTOResult.getData().getStatus().equals(0)) {
                throw new RuntimeException("文章已撤回");
            }
            
            // 调用新的审核接口记录审核信息
            articleServiceApi.reviewArticle(articleId, 1, null, reviewerId, reviewerName);
            
            return wechatDraftServiceApi.addDraft(articleDTOResult.getData());
        } catch (Exception e) {
            log.error("添加草稿并审核失败", e);
            return Result.error("操作失败: " + e.getMessage());
        }
    }

    /**
     * 拒绝审核
     * 
     * @param articleId 文章ID
     * @param rejectReason 拒绝原因
     */
    @PostMapping("/refuse/{articleId}")
    public Result<String> refuse(@PathVariable Long articleId, @RequestParam("rejectReason") String rejectReason) {
        try {
            // 自动获取当前审核人员信息
            Long reviewerId = com.microservice.common.utils.AuthUtils.requireUserId();
            String reviewerName = com.microservice.common.utils.AuthUtils.getCurrentUsername();
            
            log.info("拒绝文章: {}, 原因: {}", articleId, rejectReason);
            
            // 调用新的审核接口记录审核信息和拒绝原因
            return articleServiceApi.reviewArticle(articleId, 2, rejectReason, reviewerId, reviewerName);
        } catch (Exception e) {
            log.error("拒绝文章失败", e);
            return Result.error("拒绝失败: " + e.getMessage());
        }
    }

    /**
     * 分页查询所有用户文章
     */

    @GetMapping("/page")
    Result<PageResult<ArticleDTO>> page(
            @RequestParam(value = "current", defaultValue = "1") int current,
            @RequestParam(value = "size", defaultValue = "10") int size,
            @RequestParam(value = "status", required = false) Integer status,
            @RequestParam(value = "userId", required = false) String userName){
        return articleServiceApi.page(current,size,status,userName);
    };

    /**
     * 分页查询所有用户账号信息
     */
    @GetMapping("/users/page")
    public Result<PageResult<UserInfoDTO>> pageUsers(
            @RequestParam(value = "current", defaultValue = "1") int current,
            @RequestParam(value = "size", defaultValue = "10") int size,
            @RequestParam(value = "username", required = false) String username,
            @RequestParam(value = "status", required = false) Integer status) {
        log.info("分页查询用户列表 - current: {}, size: {}, username: {}, status: {}", 
                current, size, username, status);
        PageResult<UserInfoDTO> result = userService.pageUsers(current, size, username, status);
        return Result.success(result);
    }

    /**
     * 修改用户信息
     */
    @PutMapping("/users")
    public Result<UserInfoDTO> updateUser(@RequestBody UserUpdateDTO updateDTO) {
        log.info("修改用户信息 - userId: {}", updateDTO.getId());
        UserInfoDTO userInfo = userService.updateUser(updateDTO);
        return Result.success(userInfo);
    }

}
